import type { ConfigEnv } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import createVitePlugins from './vite'
import { createProxy } from './vite/proxy'
import { wrapperEnv, configManualChunk } from './vite/utils'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir)
}

export default defineConfig(({ command, mode }: ConfigEnv) => {
  const env = loadEnv(mode, process.cwd())
  const viteEnv = wrapperEnv(env)
  return {
    base: viteEnv.VITE_APP_BASE_URL,
    lintOnSave: false,
    resolve: {
      alias: {
        // 设置路径
        '~': pathResolve(''),
        // 设置别名
        '@': pathResolve('src') + '/'
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    server: {
      hmr: true,
      port: 9087,
      host: true,
      proxy: createProxy(viteEnv.VITE_PROXY)
    },
    build: {
      target: 'es2019',
      outDir: 'dist',
      minify: false,
      chunkSizeWarningLimit: 2000, //超过大小报警
      sourcemap: false, //构建后是否生成 source map 文件
      // 清除console和debugger
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          //对静态文件进行打包处理（文件分类）
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          // node——modules资源拆分
          manualChunks: configManualChunk
        }
      }
    },
    define: {
      VITE_APP_TITLE: JSON.stringify(env.VITE_APP_TITLE),
      VITE_APP_ENV: JSON.stringify(env.VITE_APP_ENV),
      VITE_APP_BASE_API: JSON.stringify(env.VITE_APP_BASE_API),
      VITE_APP_BASE_URL: JSON.stringify(env.VITE_APP_BASE_URL),
      'process.env': process.env
    },
    css: {
      preprocessorOptions: {
        less: {
          additionalData: `@import "src/styles/base.less";`,
          javascriptEnabled: true
        }
      }
    },
    plugins: createVitePlugins(env, command === 'build'),
    optimizeDeps: {
      include: ['mime']
    }
  }
})
